package com.q.qpicturebackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.q.qpicturebackend.annotation.AutoCheck;
import com.q.qpicturebackend.common.BaseResponse;
import com.q.qpicturebackend.common.DeleteRequest;
import com.q.qpicturebackend.common.ResultUtils;
import com.q.qpicturebackend.constant.UserConstant;
import com.q.qpicturebackend.exception.BusinessException;
import com.q.qpicturebackend.exception.ErrorCode;
import com.q.qpicturebackend.exception.ThrowUtils;
import com.q.qpicturebackend.model.dto.user.UserLoginRequestDto;
import com.q.qpicturebackend.model.dto.user.UserQueryRequestDto;
import com.q.qpicturebackend.model.dto.user.UserRegisterRequestDto;
import com.q.qpicturebackend.model.dto.user.UserUpdateRequestDto;
import com.q.qpicturebackend.model.entity.User;
import com.q.qpicturebackend.model.enums.UserRoleEnum;
import com.q.qpicturebackend.model.vo.UserLoginVo;
import com.q.qpicturebackend.model.vo.UserVo;
import com.q.qpicturebackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public BaseResponse<Long> register(@RequestBody UserRegisterRequestDto userRegisterRequestDto) {
        ThrowUtils.throwIf(userRegisterRequestDto == null, ErrorCode.PARAMS_ERROR);
        String userPassword = userRegisterRequestDto.getUserPassword();
        String userAccount = userRegisterRequestDto.getUserAccount();
        String checkPassword = userRegisterRequestDto.getCheckPassword();
        long id = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(id);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public BaseResponse<UserLoginVo> login(@RequestBody UserLoginRequestDto userLoginRequestDto, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequestDto == null, ErrorCode.PARAMS_ERROR);
        String userPassword = userLoginRequestDto.getUserPassword();
        String userAccount = userLoginRequestDto.getUserAccount();
        UserLoginVo userLoginVo = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userLoginVo);
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping("/get/login")
    @ApiOperation("获取当前登录用户")
    public BaseResponse<UserLoginVo> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        UserLoginVo userLoginVo = userService.getLoginUserVO(user);
        return ResultUtils.success(userLoginVo);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("用户注销")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 用户创建
     */
    @PostMapping("/add")
    @ApiOperation("用户创建")
    @AutoCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserRegisterRequestDto userRegisterRequestDto) {
        ThrowUtils.throwIf(userRegisterRequestDto == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userRegisterRequestDto, user);
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @ApiOperation("根据 id 获取用户（仅管理员）")
    @AutoCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    @ApiOperation("根据id获取包装类")
    public BaseResponse<UserVo> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @ApiOperation("删除用户")
    @AutoCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    @ApiOperation("更新用户")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequestDto userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("分页查询用户")
    @AutoCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVo>> listUserVOByPage(@RequestBody UserQueryRequestDto userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVo> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVo> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }


}


